package com.base.bean;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;

public class CustomDateEditor extends PropertyEditorSupport {
    private static final String FORMAT = "yyyy-MM-dd";
    
    private static final String FORMAT_FILL = "yyyy-MM-dd HH:mm:ss";
    
    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        if (StringUtils.isBlank(text)) {
            setValue(null);
            return;
        }
        text = text.trim();
        SimpleDateFormat sdf = new SimpleDateFormat(FORMAT_FILL);
        if (text.length() == 10) {
            sdf = new SimpleDateFormat(FORMAT);
        }
        try {
            setValue(sdf.parse(text));
        } catch (ParseException ex) {
            throw new IllegalArgumentException("Could not parse date: " + text, ex);
        }
    }
    
    @Override
    public String getAsText() {
        Date value = (Date) getValue();
        return (value != null ? new SimpleDateFormat(FORMAT_FILL).format(value) : "");
    }
}
